package zhoug.common.zxing.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import zhoug.common.zxing.activity.ScanCodeActivity;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultCaller;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.DefaultLifecycleObserver;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleOwner;

/**
 * 扫码启动工具
 *
 * @Author 35574
 * @Date 2020/6/28
 * @Description
 */
public class ScanCodeHelper {
    private static final String TAG = ">>>ZxingHelper";
    private Callback callback;
    private Context mContext;
    private boolean mSearchEnable = false;//是否启用右边的搜索按钮
    private boolean mChooseImageEnable = true;//是否允许选择相册中的图片识别二维码
    /**
     * 扫描框范围矩形背景是否启用
     * true:设置背景为R.drawable.zxing_scan_rect_bg
     * false:设置背景@android:color/transparent
     */
    private boolean mScanRectBgEnable = false;
    private String mSearchActivityName;//搜索页面Activity全名
    private String mSearchHintText;//搜索页面搜索框提示
    private String mTitle;//扫一扫页面标题
    private String mSaoMaDescription;//扫一扫页面的描述

    private ActivityResultLauncher<Intent> mLauncher;

    /**
     * 注意:需要在onCreate方法中或者之前创建
     *
     * @param context
     * @param caller
     * @param lifecycle
     */
    public ScanCodeHelper(@NonNull Context context, @NonNull ActivityResultCaller caller, @NonNull Lifecycle lifecycle) {
        this.mContext = context;
        lifecycle.addObserver(new DefaultLifecycleObserver() {
            @Override
            public void onCreate(@NonNull LifecycleOwner owner) {
                registerForActivityResult(caller);
            }

            @Override
            public void onDestroy(@NonNull LifecycleOwner owner) {
                if (mLauncher != null) {
                    mLauncher.unregister();
                    mLauncher = null;
                }
            }
        });
    }

    public ScanCodeHelper(@NonNull AppCompatActivity activity) {
        this(activity, activity, activity.getLifecycle());
    }

    public ScanCodeHelper(@NonNull Fragment fragment) {
        this(fragment.getContext(), fragment, fragment.getViewLifecycleOwner().getLifecycle());
    }


    /**
     * 注册activity回掉
     *
     * @param caller
     */
    private void registerForActivityResult(ActivityResultCaller caller) {
        mLauncher = caller.registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult activityResult) {
                if (callback == null) return;
                if (activityResult != null && activityResult.getResultCode() == Activity.RESULT_OK) {
                    //处理扫描结果（在界面上显示）
                    Intent data = activityResult.getData();
                    if (null != data) {
                        Bundle bundle = data.getExtras();
                        if (bundle == null) {
                            if (callback instanceof Callback2) {
                                ((Callback2) callback).onResult(Callback.CODE_FAIL, null, null, "解码错误");
                            } else {
                                callback.result(Callback.CODE_FAIL, "解码错误");
                            }
                        } else {
                            String result = bundle.getString("result");
                            if (callback instanceof Callback2) {
                                ((Callback2) callback).onResult(Callback.CODE_SUCCESS, result, bundle.getByteArray("byteArray"), null);
                            } else {
                                callback.result(Callback.CODE_SUCCESS, result);

                            }
                        }
                    } else {
                        if (callback instanceof Callback2) {
                            ((Callback2) callback).onResult(Callback.CODE_FAIL, null, null, "扫码失败");
                        } else {
                            callback.result(Callback.CODE_FAIL, "扫码失败");
                        }
                    }
                }
            }
        });

    }

    /**
     * 搜索页面搜索框提示
     *
     * @param searchHintText
     * @return
     */
    public ScanCodeHelper setSearchHintText(String searchHintText) {
        this.mSearchHintText = searchHintText;
        return this;
    }

    /**
     * 扫一扫页面标题
     *
     * @param title
     * @return
     */
    public ScanCodeHelper setTitle(String title) {
        this.mTitle = title;
        return this;
    }

    /**
     * 是否启用右边的搜索按钮
     *
     * @param searchEnable
     * @return
     */
    public ScanCodeHelper setSearchEnable(boolean searchEnable) {
        this.mSearchEnable = searchEnable;
        return this;
    }

    /**
     * 是否允许选择相册中的图片识别二维码
     *
     * @param chooseImageEnable
     * @return
     */
    public ScanCodeHelper setChooseImageEnable(boolean chooseImageEnable) {
        this.mChooseImageEnable = chooseImageEnable;
        return this;
    }

    /**
     * 搜索页面Activity全名
     *
     * @param searchActivityName
     * @return
     */
    public ScanCodeHelper setSearchActivityName(String searchActivityName) {
        this.mSearchActivityName = searchActivityName;
        return this;
    }

    /**
     * 扫一扫页面的描述
     *
     * @param description
     * @return
     */
    public ScanCodeHelper setSaoMaDescription(String description) {
        this.mSaoMaDescription = description;
        return this;
    }

    /**
     * 扫描框范围矩形背景是否启用
     *
     * @param scanRectBgEnable
     * @return
     */
    public ScanCodeHelper setScanRectBgEnable(boolean scanRectBgEnable) {
        this.mScanRectBgEnable = scanRectBgEnable;
        return this;
    }

    /**
     * 开始扫码
     */
    public void start() {
        if (mLauncher == null) {
            Log.e(TAG, "is unregister");
        }
        Intent intent = new Intent(mContext, ScanCodeActivity.class);
        initParams(intent);
        mLauncher.launch(intent);
    }

    /**
     * 设置参数
     *
     * @param intent
     */
    private void initParams(Intent intent) {
        intent.putExtra(ScanCodeActivity.PARAM_SEARCH_ENABLE, mSearchEnable);
        intent.putExtra(ScanCodeActivity.PARAM_CHOOSE_IMAGE_ENABLE, mChooseImageEnable);
        intent.putExtra(ScanCodeActivity.PARAM_SEARCH_ACTIVITY_NAME, mSearchActivityName);
        intent.putExtra(ScanCodeActivity.PARAM_SEARCH_HINT_TEXT, mSearchHintText);
        intent.putExtra(ScanCodeActivity.PARAM_TITLE, mTitle);
        intent.putExtra(ScanCodeActivity.PARAM_DESCRIPTION, mSaoMaDescription);
        intent.putExtra(ScanCodeActivity.PARAM_SCAN_RECT_BG_ENABLE, mScanRectBgEnable);
    }


    public Callback getCallback() {
        return callback;
    }

    public void setCallback(Callback callback) {
        this.callback = callback;
    }

    public interface Callback {
        int CODE_SUCCESS = 2;
        int CODE_FAIL = 1;

        /**
         * @param code {@link #CODE_FAIL,#CODE_SUCCESS}
         * @param msg
         */
        void result(int code, String msg);

    }

    public interface Callback2 extends Callback {

        /**
         * @param code {@link #CODE_FAIL,#CODE_SUCCESS}
         * @param msg
         */
        @Deprecated
        @Override
        void result(int code, String msg);

        /**
         * @param code      {@link #CODE_FAIL,#CODE_SUCCESS}
         * @param text      文本数据
         * @param byteArray 字节数据
         * @param error     错误信息
         */
        void onResult(int code, String text, byte[] byteArray, String error);

    }
}
